﻿#region Imports

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using MammothMicro.SilverSocket.Protocol.System;

#endregion

namespace MammothMicro.SilverSocket.Shared
{
    /// <summary>
    /// The default message serializer.
    /// </summary>
    public class DefaultMessageSerializer : IMessageSerializer
    {
        /// <summary>
        /// The _serializer.
        /// </summary>
        private DataContractSerializer _serializer;

        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultMessageSerializer"/> class.
        /// </summary>
        /// <param name="knownTypes">
        /// The known types.
        /// </param>
        public DefaultMessageSerializer(List<Type> knownTypes)
        {
            this._serializer = new DataContractSerializer(knownTypes[0], knownTypes.ToArray());
            this.KnownMessages = knownTypes;
        }

        public List<Type> KnownMessages{get; set; }

        #region IMessageSerializer Members

        /// <summary>
        /// The serialize.
        /// </summary>
        /// <param name="message">
        /// The message.
        /// </param>
        /// <returns>
        /// </returns>
        public List<byte> Serialize(DuplexMessage message)
        {
            var stream = new MemoryStream();
            this._serializer.WriteObject(stream, message);
            return stream.ToArray().ToList();
        }

        /// <summary>
        /// The deserialize.
        /// </summary>
        /// <param name="serializedMessage">
        /// The serialized message.
        /// </param>
        /// <returns>
        /// </returns>
        public DuplexMessage Deserialize(List<byte> serializedMessage)
        {
            var stream = new MemoryStream();
            stream.Write(serializedMessage.ToArray(), 0, serializedMessage.Count);
            stream.Position = 0;
            var obj = this._serializer.ReadObject(stream);
            return (DuplexMessage) obj;
        }

        #endregion
    }
}